﻿using System;
using System.Text;

namespace Hotel.Alliance.CommonEsLib.Tools
{
    internal static class StringCompressionHelper
    {
        /// <summary>  
        /// 将传入字符串以GZip算法压缩后，返回Base64编码字符  
        /// </summary>  
        /// <param name="rawString">需要压缩的字符串</param>  
        /// <returns>压缩后的Base64编码的字符串</returns>  
        public static string GZipCompressString(string rawString)
        {
            try
            {
                if (string.IsNullOrEmpty(rawString))
                {
                    return string.Empty;
                }
                else
                {
                    byte[] rawData = Encoding.UTF8.GetBytes(rawString);
                    byte[] zippedData = GZipHelper.Compress(rawData);

                    return Convert.ToBase64String(zippedData);
                }
            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }

        /// <summary>  
        /// 将已压缩的字符串以GZip算法解压缩  
        /// </summary>  
        /// <param name="zippedString">已压缩的字符串</param>  
        /// <returns>原始未压缩字符串</returns>  
        public static string GZipDecompressString(string zippedString)
        {
            try
            {
                if (string.IsNullOrEmpty(zippedString))
                {
                    return string.Empty;
                }
                else
                {
                    byte[] zippedData = Convert.FromBase64String(zippedString);
                    return Encoding.UTF8.GetString(GZipHelper.Decompress(zippedData));
                }
            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }
    }
}
